<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="部件名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入部件名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="图纸图号" prop="drawingNumber">
        <el-input
          v-model="queryParams.drawingNumber"
          placeholder="请输入图纸图号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="btn">
      <div>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['outsource:outbound-delivery:export']"
        >
          数据导出
        </el-button>
        <el-button
          type="primary"
          @click="goCreate"
          v-hasPermi="['outsource:outbound-delivery:create']"
        >
          创建出库单
        </el-button>
      </div>
      <div>
        <el-button type="primary" @click="openTableTitleSet">表头设置</el-button>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :height="tableHeight"
      @selection-change="handleSelectionChange"
      show-summary
      :summary-method="getSummaries"
      border
      ref="multipleTableRef"
    >
      <el-table-column
        align="center"
        type="selection"
        :reserve-selection="true"
        width="60px"
        fixed="left"
      />
      <el-table-column label="序号" align="center" type="index" width="60px" fixed="left" />
      <template v-for="(item, index) in tableTitleList">
        <el-table-column
          v-if="item.isTable && item.type !== 'index'"
          :key="index"
          :min-width="item.width"
          :label="item.label"
          :prop="item.field"
          :align="item.align"
          :type="item.type"
          :header-align="item.headerAlign"
        >
          <template #default="scope">
            <el-input-number
              v-nextInput="'outboundDeliveryQuantity'"
              name="outboundDeliveryQuantity"
              v-if="['outboundDeliveryQuantity'].includes(item.field)"
              v-model="scope.row[item.field]"
              :precision="2"
              :min="0"
              :max="scope.row.stockQuantity"
            />
            <template v-else>
              <dict-tag :type="item.dictType" :value="scope.row[item.field]" v-if="item.dictType" />
              <div v-else>{{ scope.row[item.field] }}</div>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getList" />
</template>

<script setup lang="ts" name="OutboundDelivery">
import download from '@/utils/download'
import * as OutboundDeliveryApi from '@/api/outsource/outsourceInAndOutStorage/outboundDelivery'
import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache()
const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 50,
  productNumber: null,
  partName: null,
  drawingNumber: null
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const tableTitleList = ref<CrudSchema[]>([]) //表头
const code = 'OutboundDelivery' //表头名
const tableHeight = ref(0)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OutboundDeliveryApi.getOutboundDeliveryPage(queryParams)
    list.value = data.list
    tableTitleList.value = data.labels
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 打开表头设置
const tableTitleSet = ref()
const openTableTitleSet = () => {
  tableTitleSet.value.open(tableTitleList.value, code)
}

// 合计行
const getSummaries = (param) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (['stockQuantity', 'outboundDeliveryQuantity'].includes(column.property)) {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
          } else {
            return parseFloat(prev).toFixed(2)
          }
        }, 0)
      } else {
        sums[index] = ''
      }
    }
  })
  return sums
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const { push } = useRouter() // 路由

// 创建入库单
const goCreate = () => {
  if (!multipleSelection.value.length) {
    message.notifyError('请选择至少一条数据')
    return
  }
  wsCache.set(CACHE_KEY.OUT_STORAGE, multipleSelection.value)
  push({
    path: '/outsource/outsource/warehousingOutbound/outboundDeliveryDetail'
  })
}

/** 导出按钮操作 */
const exportRef = ref()
const handleExport = () => {
  exportRef.value.open()
}

// 多选
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 下载
const multipleTableRef = ref()
const downloadFun = async () => {
  const val = exportRef.value.params
  const params = {
    fileName: val.name,
    ids: []
  }
  if (val.range === 'all') {
    params.ids = []
  } else {
    params.ids = multipleSelection.value.map((item) => {
      return item['id']
    })
  }
  const data = await OutboundDeliveryApi.exportOutboundDelivery(params)
  download.excel(data, val.name)
  multipleTableRef.value!.clearSelection()
  multipleSelection.value = []
}

/** 初始化 **/
onMounted(() => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 115
  getList()
})
</script>
<style lang="scss" scoped>
.btn {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style>
